package com.cac.demo.controller.partSalesReturn;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cac.demo.controller.compressedFiles.CompressedFilesEditor;
import com.cac.demo.entity.materialScan.WmsDeliverPlanDTO;
import com.cac.demo.entity.wmsReturnApply.WmsReturnApplyDTO;
import com.cac.demo.newCode.materialStorage.entity.WmsItemInventory;
import com.cac.demo.newCode.materialStorage.entity.WmsReturnApply;
import com.cac.demo.newCode.materialStorage.service.IWmsItemInventoryService;
import com.cac.demo.newCode.materialStorage.service.IWmsReturnApplyService;
import com.cac.demo.service.partSalesReturn.PartSalesReturnService;
import com.cac.demo.util.adapter.*;
import com.fasterxml.jackson.core.type.TypeReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.cac.demo.util.adapter.BusinessUtil.getSortExpColumnName;

@RestController
@RequestMapping("/partSalesReturn/")
public class PartSalesReturnRest {
    @Autowired
    private PartSalesReturnService partSalesReturnService;
    @Resource
    private Environment environment;
    @Resource
    private CompressedFilesEditor compressedFilesEditor;
    @Resource
    private IWmsReturnApplyService iWmsReturnApplyService;
    @Resource
    private IWmsItemInventoryService wmsItemInventoryService;

    /**
     * 创建退货单
     * @param map
     * @return
     */
    @PostMapping("/creatReturnSales")
    public ResponseMsg<Integer> creatReturnSales(@RequestBody Map map){
        ArrayList<LinkedHashMap<String,String>> list = (ArrayList<LinkedHashMap<String, String>>) map.get("data");
        ResponseMsg<Integer> responseMsg =  new ResponseMsg<>();
        String message = "";
        for (Map map1 : list) {
            int msg = partSalesReturnService.insertWmsReturnApply(map1);
            if(msg == 1){
                message+="图号为"+map1.get("itemCode")+"创建退货单成功！";
//                responseMsg.setMessage("成功创建退货单！").setRetCode("200");
            }else if (msg == -2){
                message+="图号为"+map1.get("itemCode")+"创建退货单失败！退库数量大于现有库存数量";
//                responseMsg.setMessage("创建退货单失败！退库数量大于现有库存数量").setRetCode("201");
            }else if (msg == -3){
                message+="图号为"+map1.get("itemCode")+"创建退货单失败！退库数量不能包含已被非离库占用的数量！";
//                responseMsg.setMessage("创建退货单失败！退库数量不能包含已被非离库占用的数量！").setRetCode("201");
            }else{
                responseMsg.setMessage("创建退货单失败！").setRetCode("201");
            }
        }
        responseMsg.setMessage(message);
        return responseMsg;
    }
    //零件退货页面条件查询
    @PostMapping("/searchParamsByReturn")
    public ResponseMsg<QueryRespBean<WmsReturnApplyDTO>> searchParamsBy(@RequestBody Map map) {
        ResponseMsg<QueryRespBean<WmsReturnApplyDTO>> responseMsg = new ResponseMsg<>();
        //时间范围
        LinkedHashMap startTimeParams=(LinkedHashMap) map.get("searchParams");
        String startTimeNew= JSON.toJSONString(startTimeParams.get("startTime"));
        Date startTime = JSON.parseObject(startTimeNew, Date.class);
        Date endTime =null;
        if(!Objects.isNull(startTimeParams.get("endTime"))&&!startTimeParams.get("endTime").toString().equals("")){
            String endTimeParams = JSON.toJSONString(startTimeParams.get("endTime"));
            endTime = JSON.parseObject(endTimeParams, Date.class);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(endTime);
            calendar.add(Calendar.DATE, 1);
            endTime=calendar.getTime();
        }
        //分页
        String param = JSON.toJSONString(map.get("pageParameter"));
        PageParameter pageParameter = JSON.parseObject(param, PageParameter.class);
        //查询条件
        String searchParamsParams = JSON.toJSONString(map.get("searchParams"));
        WmsReturnApplyDTO searchParams = JSON.parseObject(searchParamsParams, WmsReturnApplyDTO.class);

        QueryReqBean<WmsReturnApplyDTO> queryReqBean = new QueryReqBean<>();
        queryReqBean.setSearchParams(searchParams);
        queryReqBean.setPageParameter(pageParameter);

        if (StringUtils.hasText(queryReqBean.getSidx()) && StringUtils.hasText(queryReqBean.getSord())) {
            String sordExp = getSortExpColumnName(queryReqBean.getSidx(), queryReqBean.getSord(), WmsReturnApplyDTO.class);
            if (StringUtils.hasText(sordExp)) {
                queryReqBean.setSortExp(sordExp);
            }
        }
        if (StringUtils.hasText(queryReqBean.getKeyWord())) {
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            WmsReturnApplyDTO searchKeyWordParam = JsonHelper.getInstance().readValue(queryReqBean.getKeyWord(), dateFormat, new TypeReference<WmsReturnApplyDTO>() {
            });
            queryReqBean.setSearchParams(searchKeyWordParam);
        }

        QueryRespBean<WmsReturnApplyDTO> result = partSalesReturnService.selectReturnApply(queryReqBean, ContextCommonHolder.getOrgId(), queryReqBean.getSortExp(), startTime, endTime);
        responseMsg.setResponseBody(result);
        return responseMsg;
    }
    //成品退货页面条件查询
    @PostMapping("/searchParamsByProductReturn")
    public ResponseMsg<QueryRespBean<WmsReturnApplyDTO>> searchParamsByProduct(@RequestBody Map map) {
        ResponseMsg<QueryRespBean<WmsReturnApplyDTO>> responseMsg = new ResponseMsg<>();
        //时间范围
        LinkedHashMap startTimeParams=(LinkedHashMap) map.get("searchParams");
        String startTimeNew= JSON.toJSONString(startTimeParams.get("startTime"));
        String endTimeNew= JSON.toJSONString(startTimeParams.get("endTime"));
        Date startTime = JSON.parseObject(startTimeNew, Date.class);
        Date endTime = JSON.parseObject(endTimeNew, Date.class);
        //分页
        String param = JSON.toJSONString(map.get("pageParameter"));
        PageParameter pageParameter = JSON.parseObject(param, PageParameter.class);
        //查询条件
        String searchParamsParams = JSON.toJSONString(map.get("searchParams"));
        WmsReturnApplyDTO searchParams = JSON.parseObject(searchParamsParams, WmsReturnApplyDTO.class);

        QueryReqBean<WmsReturnApplyDTO> queryReqBean = new QueryReqBean<>();
        queryReqBean.setSearchParams(searchParams);
        queryReqBean.setPageParameter(pageParameter);

        if (StringUtils.hasText(queryReqBean.getSidx()) && StringUtils.hasText(queryReqBean.getSord())) {
            String sordExp = getSortExpColumnName(queryReqBean.getSidx(), queryReqBean.getSord(), WmsReturnApplyDTO.class);
            if (StringUtils.hasText(sordExp)) {
                queryReqBean.setSortExp(sordExp);
            }
        }
        if (StringUtils.hasText(queryReqBean.getKeyWord())) {
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            WmsReturnApplyDTO searchKeyWordParam = JsonHelper.getInstance().readValue(queryReqBean.getKeyWord(), dateFormat, new TypeReference<WmsReturnApplyDTO>() {
            });
            queryReqBean.setSearchParams(searchKeyWordParam);
        }

        QueryRespBean<WmsReturnApplyDTO> result = partSalesReturnService.selectReturnApplyProduct(queryReqBean, ContextCommonHolder.getOrgId(), queryReqBean.getSortExp(), startTime, endTime);
        responseMsg.setResponseBody(result);
        return responseMsg;
    }
    //零件配送页面条件查询
    @PostMapping("/searchParamsByDelivery")
    public ResponseMsg<QueryRespBean<WmsDeliverPlanDTO>> searchParamsByDelivery(@RequestBody Map map) {
        ResponseMsg<QueryRespBean<WmsDeliverPlanDTO>> responseMsg = new ResponseMsg<>();
        //分页
        String param = JSON.toJSONString(map.get("pageParameter"));
        PageParameter pageParameter = JSON.parseObject(param, PageParameter.class);
        //查询条件
        String searchParamsParams = JSON.toJSONString(map.get("searchParams"));
        WmsDeliverPlanDTO searchParams = JSON.parseObject(searchParamsParams, WmsDeliverPlanDTO.class);

        QueryReqBean<WmsDeliverPlanDTO> queryReqBean = new QueryReqBean<>();
        queryReqBean.setSearchParams(searchParams);
        queryReqBean.setPageParameter(pageParameter);

        if (StringUtils.hasText(queryReqBean.getSidx()) && StringUtils.hasText(queryReqBean.getSord())) {
            String sordExp = getSortExpColumnName(queryReqBean.getSidx(), queryReqBean.getSord(), WmsDeliverPlanDTO.class);
            if (StringUtils.hasText(sordExp)) {
                queryReqBean.setSortExp(sordExp);
            }
        }
        if (StringUtils.hasText(queryReqBean.getKeyWord())) {
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            WmsDeliverPlanDTO searchKeyWordParam = JsonHelper.getInstance().readValue(queryReqBean.getKeyWord(), dateFormat, new TypeReference<WmsDeliverPlanDTO>() {
            });
            queryReqBean.setSearchParams(searchKeyWordParam);
        }

        QueryRespBean<WmsDeliverPlanDTO> result = partSalesReturnService.selectDeliverPlan(queryReqBean, ContextCommonHolder.getOrgId(), queryReqBean.getSortExp());
        responseMsg.setResponseBody(result);
        return responseMsg;
    }
    //成品配送页面条件查询
    @PostMapping("/searchParamsByDeliveryProduct")
    public ResponseMsg<QueryRespBean<WmsDeliverPlanDTO>> searchParamsByDeliveryProduct(@RequestBody Map map) {
        ResponseMsg<QueryRespBean<WmsDeliverPlanDTO>> responseMsg = new ResponseMsg<>();
        //分页
        String param = JSON.toJSONString(map.get("pageParameter"));
        PageParameter pageParameter = JSON.parseObject(param, PageParameter.class);
        //查询条件
        String searchParamsParams = JSON.toJSONString(map.get("searchParams"));
        WmsDeliverPlanDTO searchParams = JSON.parseObject(searchParamsParams, WmsDeliverPlanDTO.class);

        QueryReqBean<WmsDeliverPlanDTO> queryReqBean = new QueryReqBean<>();
        queryReqBean.setSearchParams(searchParams);
        queryReqBean.setPageParameter(pageParameter);

        if (StringUtils.hasText(queryReqBean.getSidx()) && StringUtils.hasText(queryReqBean.getSord())) {
            String sordExp = getSortExpColumnName(queryReqBean.getSidx(), queryReqBean.getSord(), WmsDeliverPlanDTO.class);
            if (StringUtils.hasText(sordExp)) {
                queryReqBean.setSortExp(sordExp);
            }
        }
        if (StringUtils.hasText(queryReqBean.getKeyWord())) {
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            WmsDeliverPlanDTO searchKeyWordParam = JsonHelper.getInstance().readValue(queryReqBean.getKeyWord(), dateFormat, new TypeReference<WmsDeliverPlanDTO>() {
            });
            queryReqBean.setSearchParams(searchKeyWordParam);
        }

        QueryRespBean<WmsDeliverPlanDTO> result = partSalesReturnService.selectDeliverPlanProduct(queryReqBean, ContextCommonHolder.getOrgId(), queryReqBean.getSortExp());
        responseMsg.setResponseBody(result);
        return responseMsg;
    }
    //修改退货单数据
    @PostMapping("/updateReturnApply")
    public ResponseMsg<Integer> update(@RequestBody WmsReturnApplyDTO wmsReturnApplyDTO){
        ResponseMsg<Integer> responseMsg = new ResponseMsg<>();
        responseMsg.setResponseBody(partSalesReturnService.updateWmsReturnApply(wmsReturnApplyDTO));
        return responseMsg;
    }

    //删除退货单数据
    @PostMapping("/deleteReturnApplyByIds")
    public ResponseMsg<Map> deleteByIds(@RequestBody HashMap map) {
        ResponseMsg<Map> responseMsg = new ResponseMsg<>();
        Map resMap = new HashMap();
        int  s=0,f=0;
        List<HashMap> listmap = (List<HashMap>) map.get("data");
        if(listmap.size()==0){
            return responseMsg.setRetCode("201").setMessage("请选中需要删除的数据");
        }
        for( int i=0;i<listmap.size();i++)
        {
            HashMap<String, Object> map1;
            map1=listmap.get(i);
            if("编辑中".equals(map1.get("returnStatus")))
            {
                partSalesReturnService.deleteWmsReturnApplyByIds(map1);
                s++;

            }
            else
            {
                f++;
            }
        }
        if(s==0&&f!=0)
        {
            responseMsg.setRetCode("201");
            responseMsg.setMessage("删除失败！");
        }
        if(f==0&&s!=0)
        {
            responseMsg.setRetCode("200");
            responseMsg.setMessage("删除成功！");
        }
        else
        {
            resMap.put("成功数",s);
            resMap.put("失败数",f);
            responseMsg.setResponseBody(resMap);
            responseMsg.setRetCode("202");
        }


        //        java.util.List<String> wmsReturnApplyIds  = (java.util.List<String>) map.get("wmsReturnApplyId");
//        java.util.List<String> returnStatus  = (java.util.List<String>) map.get("returnStatus");
//
//
        return responseMsg;
    }
    //提交退货单信息
    @PostMapping("/submitReturnSales")
    public  ResponseMsg<Map> submitReturn(@RequestBody HashMap<String, Object> maps) {
        ResponseMsg<Map> responseMsg = new ResponseMsg<>();
        Map reMsg = new HashMap();
        int s = 0;
        int f = 0;
        List<HashMap<String, Object>> listMap = (List<HashMap<String, Object>>) maps.get("data");
        if(listMap.size()==0){
            return responseMsg.setRetCode("201").setMessage("请选择退货单");
        }
        for (int i = 0; i < listMap.size(); i++) {
            HashMap<String, Object> map = listMap.get(i);
            if ("编辑中".equals(map.get("returnStatus"))) {
                String wmsReturnApplyId = (String) map.get("wmsReturnApplyId");
                partSalesReturnService.changeReturnType(wmsReturnApplyId);
                //查出退库单数据
                LambdaQueryWrapper<WmsReturnApply> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(WmsReturnApply::getWmsReturnApplyId, wmsReturnApplyId);
                WmsReturnApply wmsReturnApply = iWmsReturnApplyService.getOne(queryWrapper);
                LambdaQueryWrapper<WmsItemInventory> queryWrapper1 = new LambdaQueryWrapper<>();
                queryWrapper1.eq(WmsItemInventory::getWmsDeliveryPlanId,wmsReturnApply.getWmsDeliveryPlanId());
                WmsItemInventory wmsItemInventory = wmsItemInventoryService.getOne(queryWrapper1);
                //定义json对象存储数据，打包发送到Cemop
                JSONArray jsonArray = new JSONArray();
                JSONObject json = new JSONObject();
                json.put("momWmsReturnApplyId", wmsReturnApply.getWmsReturnApplyId());    //退库单id
                json.put("momWmsDeliveryPlanId", wmsReturnApply.getWmsDeliveryPlanId());    //交接单id
                json.put("momWmsItemInventoryId", wmsItemInventory.getWmsItemInventoryId()); // 台账id
                json.put("wdrwblEcd", wmsReturnApply.getBillNo()); // 退库单号
                json.put("srtpCd", wmsReturnApply.getSourceType()); // 来源类型1-专业厂交接退库;2-ERP交接退库;3-DXE交接退库
                json.put("constkTypCd", wmsReturnApply.getReturnType()); // 退库类型1-无故障退库;2-执行质量通知单退库;3-故障单退库
                json.put("constkStusCd",wmsReturnApply.getReturnStatus()); // 退库状态:1-编辑中;2-待接收;3-待确认;4-保管待接收;5-已驳回;6-结束;7-删除
                json.put("constkQty", wmsReturnApply.getReturnQty()); // 退库数量
                json.put("userId", wmsReturnApply.getApplyEmpCode()); // 退库人工号
                json.put("aplyTypCd",wmsReturnApply.getApplyType()); // 申请类型1-原接收单位发起;2-原移交单位发起
                json.put("constkDevolBcpltNo", wmsReturnApply.getReturnDeliveryShop()); // 退库移交分厂
                json.put("constkAcrdgasEcd", wmsReturnApply.getAccordingNo()); // 退库依据
                json.put("faultPhnmnDesc",wmsReturnApply.getFailureDesc()); // 故障现象
                json.put("rlthgExtrorStusDesc",wmsReturnApply.getAppearanceStatus()); // 实物外观状态
                json.put("rlthgAsortStusDesc",wmsReturnApply.getEquipStatus()); // 实物配套状态
                json.put("oilslDate", wmsReturnApply.getSealDate()); // 油封期 时间类型
                json.put("lngstSfkepDate",wmsReturnApply.getMaxStorageDate()); // 最长保管期 时间类型
                json.put("remrkDesc",wmsReturnApply.getRemark()); // 备注
                json.put("htblEcd",wmsReturnApply.getTroubleNo()); // 故障单号
                if (wmsReturnApply.getYnWorkLineFlag().equals("是"))
                {
                    json.put("repmtPlnFlg","Y");
                }
                else {
                    json.put("repmtPlnFlg","N");
                }
                jsonArray.add(json);

                String CemopUrl = environment.getProperty("cemopUrl.returnApply");
                System.out.println("==================1.5库存提交退库申请通知Cemop接口数据================:"+jsonArray.toString());
                String path = compressedFilesEditor.generateZip(jsonArray.toString()); //将json转换为zip文件 url
                compressedFilesEditor.fileSend(jsonArray.toString(),path, CemopUrl,"库存提交退库申请通知Cemop接口数据");
                s++;
            } else f++;
        }
        reMsg.put("成功：", s);
        reMsg.put("失败：", f);
        if (s == 0 && f != 0) {
            responseMsg.setRetCode("201");
            responseMsg.setMessage("提交失败！");

        }
        if (s != 0 && f == 0) {
            responseMsg.setRetCode("200");
            responseMsg.setMessage("提交成功！");
        }
        if (s != 0 && f != 0) {
            responseMsg.setRetCode("202");
            responseMsg.setMessage("提交有失败项！");
            responseMsg.setResponseBody(reMsg);
        }
        return responseMsg;
    }

    @PostMapping("/searchWorkbinMaterial")
    public List<HashMap> searchWorkbinMaterial(@RequestBody HashMap map){
        return partSalesReturnService.searchWorkbinMaterial(map);
    }
}
